package com.cci.kangdao.service.impl;

import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.cipFleet.service.CipFleetService;
import com.cci.kangdao.cipapi.ActionEnum;
import com.cci.kangdao.cipapi.CipApiUtils;
import com.cci.kangdao.crmapi.CRMApiUtils;
import com.cci.kangdao.dao.CustomerEngineRelDao;
import com.cci.kangdao.dao.DictionariesTDao;
import com.cci.kangdao.dao.ServiceAgrementDao;
import com.cci.kangdao.dao.model.CustomerEngineRelT;
import com.cci.kangdao.dao.model.ServiceAgreement;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.dto.request.AccountEngineRelaRequest;
import com.cci.kangdao.dto.request.GetLicensePlateNumberByEsnRequest;
import com.cci.kangdao.externalData.service.ExternalDataSynchroService;
import com.cci.kangdao.service.AsyncCrmService;
import com.cci.kangdao.service.ServiceAgreementService;
import com.cci.kangdao.service.SyncEsnAndUserId;
import com.cci.kangdao.utilTool.*;
import com.gexin.fastjson.JSON;
import net.sf.json.JSONArray;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("serviceAgreementService")
public class ServiceAgreementServiceImpl implements ServiceAgreementService {

	private Logger log = Logger.getLogger(this.getClass().getName());

	@Autowired
	private ServiceAgrementDao saDao;
	@Resource
	private AsyncCrmService asyncCrmService;

	@Resource
	private CustomerEngineRelDao customerEngineRelDao;

	@Autowired
	private SyncEsnAndUserId syncEsnAndUserId;

	@Resource
	private DictionariesTDao dictionariesTDao;
	@Resource
	private ExternalDataSynchroService externalDataSynchroService;
	@Resource
	private CipFleetService cipFleetService;

	@Override
	public ModelAndView getServicePhone(HttpServletResponse response) {
		UserT userT = UserThreadLocal.get();

		if (null == userT) {
			ParameterTool.writeErrorResponse(response, -5);
			return null;
		}
		
		String servicePhone = saDao.getServicePhone(userT.getId());
		
		Map<String, String> map = new HashMap<>();
		map.put("servicePhone", StringUtils.isBlank(servicePhone)? "": servicePhone);
		
		ParameterTool.writeSuccessResponse(response, map);
		return null;
	}

	@Override
	public ModelAndView getServiceAggrementDetail(HttpServletRequest request, HttpServletResponse response) {
		UserT userT = UserThreadLocal.get();
		
		if(null == userT) {
			ParameterTool.writeErrorResponse(response, -5);
			return null;
		}
		
		String type = request.getParameter("type");
		if(StringUtils.isBlank(type)) {
			ParameterTool.writeErrorResponse(response, -5);
			return null;
		}
		int typeInt = Double.valueOf(type).intValue();
		//获取用户协议签署信息
		ServiceAgreement sa = null;
		if(typeInt == 1){   //服务站人员
			sa = saDao.getServiceAggrementDetailByZZ(typeInt,userT.getServiceStationID());
		}else{
			sa = saDao.getServiceAggrementDetail(userT.getId(), typeInt);
		}

		Map<String, Object> map = new HashMap<>();
		
		if(null != sa) {
			//已签署协议
			map.put("hasSigned", 1);
			
			Map<String, String> timeInfo = new HashMap<>();
			timeInfo.put("signTime", sa.getSignTime());
			timeInfo.put("terminateTime", sa.getTerminateTime());
			timeInfo.put("recordId", sa.getId().toString());
			
			map.put("timeInfo", timeInfo);
		} else {
			//未签署协议
			map.put("hasSigned", 0);
		}
		
		ParameterTool.writeSuccessResponse(response, map);
		return null;
	}

	@Override
	public ModelAndView signServiceAgreement(HttpServletRequest request, HttpServletResponse response) {
		UserT userT = UserThreadLocal.get();
		String type = request.getParameter("type");

		if(null == userT || StringUtils.isBlank(type)) {
			ParameterTool.writeErrorResponse(response, -5);
			return null;
		}
		
		int type_no = Double.valueOf(type).intValue();
		
		//获取用户协议签署信息
		//获取用户协议签署信息
		ServiceAgreement sa = null;
		if(type_no == 1){  //服务站人员
			sa = saDao.getServiceAggrementDetailByZZ(type_no,userT.getServiceStationID());
		}else{
			if (type_no == 3) {
				String coreManagerAgreement = dictionariesTDao.getListByDTableName("CoreManagerAgreement");
				sa = saDao.getServiceAggrementDetailAndVersion(userT.getId(), LocalTimeUtil.getRealCurrentTime(), type_no, Integer.valueOf(coreManagerAgreement));
			} else {
				sa = saDao.getServiceAggrementDetail(userT.getId(), type_no);
			}
		}
		//如已签署，则提示用户无需签署
		if(null != sa) {
			ParameterTool.writeResponse(response, 1, "您已签署协议");
			return null;
		}
		
		//签署协议
		sa = new ServiceAgreement();
		sa.setUserId(userT.getId());
		sa.setSignTime(Date_Util.getOnlyDate());
		
		if(type_no == 1) {
			sa.setTerminateTime(Date_Util.addMonth(3));
		} else {
			sa.setTerminateTime(Date_Util.addMonth(60));
		}

		sa.setCreator(userT.getId());
		sa.setCreateTime(LocalTimeUtil.getRealCurrentTime());
		sa.setType(type_no);
		if (type_no == 1) { //服务站人员  需要插入服务站主键id
			sa.setServiceStationId(userT.getServiceStationID());
		}
		if (type_no == 3) {
			String coreManagerAgreement = dictionariesTDao.getListByDTableName("CoreManagerAgreement");
			sa.setVersion(Integer.valueOf(coreManagerAgreement));

		}

		int count = saDao.signServiceAgreement(sa);

		if (count == 0) {
			ParameterTool.writeResponse(response, 1, "您已签署协议");
			return null;
		}
		if ("0".equals(type)) {
			//sprint26需求，需要将签署主动服务协议的用户信息及设备信息同步至SalesForce,此方法为异步
			asyncCrmService.syncServiceAgreementAndEngineToCRM(userT, null, true, false);
			//同步esn给cip
			List<CustomerEngineRelT> esnEngList = customerEngineRelDao.getEsnList(userT.getId());
			if(CollectionUtils.isNotEmpty(esnEngList)){
				for(CustomerEngineRelT esn : esnEngList){
					List<String> esnList = new ArrayList<>();
					esnList.add(esn.getEsn());
					CipApiUtils.getCipServiceApi().synchronizationEsn(ActionEnum.ADD.getValue(), esnList,esn.getBusinessNo());

				}
			}
			//月度报告实时更新ESN  同步给春卷团队
			syncEsnAndUserId.asSyncEsnAndUserIdAddByuserId(userT.getId());
			//同步老友会车辆
			externalDataSynchroService.pushLyhEsnList(userT.getId(),"ADD");
			//更新车队
			cipFleetService.updateFleetListByUserId(userT.getId());
		}

		ParameterTool.writeSuccessResponse(response);
		return null;
	}

	@Override
	public ModelAndView terminateServiceAgreement(HttpServletResponse response, String recordId) {
		
		if(StringUtils.isBlank(recordId)) {
			ParameterTool.writeErrorResponse(response, -5);
			return null;
		}
		
		UserT userT = UserThreadLocal.get();
		
		if(null == userT) {
			ParameterTool.writeErrorResponse(response, -5);
			return null;
		}
		//更新签署记录
		ServiceAgreement sa = new ServiceAgreement();
		sa.setDeleter(userT.getId());
		sa.setDeleteTime(LocalTimeUtil.getRealCurrentTime());
		sa.setId(Long.valueOf(recordId));
		ServiceAgreement serviceAgreement = saDao.selectById(Long.valueOf(recordId));
		int count = saDao.terminateServiceAgreement(sa);
		if (count == 0) {
			ParameterTool.writeErrorResponse(response, -99);
			return null;
		}
		if (serviceAgreement.getType() != null && serviceAgreement.getType().intValue() == 0) {
			//sprint26需求，需要将解除主动服务协议的用户信息及设备信息同步至SalesForce,此方法为异步
			asyncCrmService.syncServiceAgreementAndEngineToCRM(userT, null, false, false);
			//同步esn给cip
			List<CustomerEngineRelT> esnEngList = customerEngineRelDao.getEsnList(userT.getId());
			if(CollectionUtils.isNotEmpty(esnEngList)){
				for(CustomerEngineRelT esn : esnEngList){
					List<String> esnList = new ArrayList<>();
					esnList.add(esn.getEsn());
					CipApiUtils.getCipServiceApi().synchronizationEsn(ActionEnum.DELLETE.getValue(), esnList,esn.getBusinessNo());

				}
			}
			//月度报告实时更新ESN  同步给春卷团队
			syncEsnAndUserId.asSyncEsnAndUserIdDelByuserId(userT.getId());
			//同步老友会车辆
			externalDataSynchroService.pushLyhEsnList(userT.getId(),"DEL");
		}
		ParameterTool.writeSuccessResponse(response);
		return null;
	}

	@Override
	public ModelAndView resynchronize(HttpServletResponse response, String param) {
		AccountEngineRelaRequest accountEngineRelaRequest = JsonUtils.toJavaObject(param, AccountEngineRelaRequest.class);
		CRMApiUtils.getCRMServiceApi().syncServiceAgreementAndEngineToCRM(accountEngineRelaRequest);
		ParameterTool.writeSuccessResponse(response);
		return null;
	}

	@Override
	@Transactional
	public ModelAndView getLicensePlateNumberByEsn( String paramStr, HttpServletRequest request,
												   HttpServletResponse response) throws Exception {
		//SmsUtils.sendMessage("15230112379","ljktest152");
		//SmsUtils.sendMessage("17695988493","lctest176");
		JSONObject obj = new JSONObject();
		//1.提取参数信息
		GetLicensePlateNumberByEsnRequest licensePlateNumberByEsnRequest = JSON.parseObject(paramStr, GetLicensePlateNumberByEsnRequest.class);
		//2.校验参数是否必填，token是否正确
		String systime = licensePlateNumberByEsnRequest.getSystime();
		String token = licensePlateNumberByEsnRequest.getToken();
		List<String> esnList = licensePlateNumberByEsnRequest.getEsnList();
		if(StringUtils.isEmpty(systime) || StringUtils.isEmpty(token) || CollectionUtils.isEmpty(esnList)){
			ParameterTool.writeResponse(response, 17,"缺少必要参数！");
			return null;
		}
		if(!token.equals(PublicTool.compute(String.format("%s+%s", "CCI", systime)))){
			ParameterTool.writeResponse(response, -1,"token错误！");
			return null;
		}
		List<Map<String,Object>> licensePlateNumberByEsnList = saDao.getLicensePlateNumberByEsn(esnList);
		//根据需求如果esn或者车牌号在系统不存在，返回结果中也要将该esn返回(并且返回的顺序和传进来的esn顺序保持一致)，只不过车牌号为空，下面做遍历处理
		Map<String,Object> newMap = new HashMap<>();
		if(!CollectionUtils.isEmpty(licensePlateNumberByEsnList)){
			licensePlateNumberByEsnList.stream().forEach(licensePlateNumberByEsn->{
				String esn = MapUtils.getString(licensePlateNumberByEsn,"esn","");
				String licensePlateNumber = MapUtils.getString(licensePlateNumberByEsn,"licensePlateNumber","");
				//sprint43需求变更   多返回用户真实姓名，头像和用户是否有效字段
				String contact = MapUtils.getString(licensePlateNumberByEsn,"contact","");
				String photoUrl = MapUtils.getString(licensePlateNumberByEsn,"photoUrl","");
				String userStatus = MapUtils.getString(licensePlateNumberByEsn,"userStatus","-1");
				if(StringUtils.isNotEmpty(esn)){
					if(StringUtils.isNotEmpty(licensePlateNumber)){
						newMap.put(esn,licensePlateNumber);
					}
					List<String> esnMsgList = new ArrayList<>();
					esnMsgList.add(contact);
					esnMsgList.add(photoUrl);
					esnMsgList.add(userStatus);
					newMap.put(esn+"MsgList",esnMsgList);
				}
			});
		}
		List<Map<String,Object>> returnMapList = new ArrayList<>();
		esnList.stream().forEach(esn->{
			Map<String,Object> returnMap = new HashMap<>();
			returnMap.put("esn",esn);
			returnMap.put("licensePlateNumber",MapUtils.getString(newMap,esn,""));
			Object o = newMap.get(esn+"MsgList");
			if(null != o){
				JSONArray esnMsgList = JSONArray.fromObject(o);
				returnMap.put("contact",null!=esnMsgList.get(0)?esnMsgList.get(0):"");
				returnMap.put("photoUrl",null!=esnMsgList.get(1)?esnMsgList.get(1):"");
				returnMap.put("userStatus",null!=esnMsgList.get(2)?esnMsgList.get(2):-1);
			}else{
				returnMap.put("contact","");
				returnMap.put("photoUrl","");
				returnMap.put("userStatus",-1);
			}
			returnMapList.add(returnMap);
		});

		try {
			obj.put("data",returnMapList);
			obj.put("status", 0);
			obj.put("msg", "success");
			ParameterTool.writeResponse(response, obj.toString());
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			String msg = "{\"status\": -99,\"msg\": \"未知错误\"}";
			ParameterTool.writeResponse(response, msg);
			return null;
		}
		return null;
	}
}
